<template>
  <canvas ref="container" class="w-full h-full"></canvas>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { WebGL } from "../../lib/webgl/WebGL";

const container = ref(null);
const webgl = new WebGL();

const triangle = {
  vertex: new Float32Array([0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0]),
  vertexCount: 3,
};

function initShader(gl) {
  let vertexShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(
    vertexShader,
    `
      attribute vec3 a_Position;
      varying vec4 v_Position;
      void main() {
        gl_Position = vec4(a_Position, 1.0);
        v_Position = (vec4(a_Position, 1.0) + vec4(1.0, 1.0, 1.0, 1.0)) * 0.5;
      }
      `
  );
  gl.compileShader(vertexShader);

  let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(
    fragmentShader,
    `
      precision mediump float;
      varying vec4 v_Position;
      void main() {
        gl_FragColor = v_Position;
      }
      `
  );
  gl.compileShader(fragmentShader);

  let program = gl.createProgram();
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  gl.linkProgram(program);

  gl.useProgram(program);
  gl.program = program;
}

function draw(gl) {
  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, triangle.vertex, gl.STATIC_DRAW);

  let a_Position = gl.getAttribLocation(gl.program, "a_Position");
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(a_Position);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, triangle.vertexCount);
}

function init() {
  let canvas = container.value;
  let gl = webgl.initWebGL(canvas);
  initShader(gl);
  draw(gl);

  window.addEventListener("resize", () => {
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    gl.viewport(0, 0, canvas.width, canvas.height);
  });
}

onMounted(() => {
  init();
});
</script>
